package com.dkhseep.bigevent.interceptor;

import com.dkhseep.bigevent.util.JwtUtil;
import com.dkhseep.bigevent.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 功能:
 * 作者:Dksheep
 * 日期:2024/10/816:40
 */
@Component
public class Logininterceptor implements HandlerInterceptor {
    @Autowired private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            Map<String,Object> claims = JwtUtil.parseToken(token); //用于解析一个给定的 JWT 字符串（token），并返回一个包含 JWT 中声明的业务数据的 Map<String, Object>。这个 Map 通常包含了在生成 JWT 时添加的各种键值对，比如用户信息、权限、令牌的有效期等
            String username = (String) claims.get("username");
            ThreadLocalUtil.set(claims);//存入线程局部变量
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            if(operations.get(username)==null||!operations.get(username).equals(token)) //校验token
                throw new RuntimeException();
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成后 清空ThredLocal中的数据 防止内存泄漏
        ThreadLocalUtil.remove();
    }
}
